<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\WxMiniprogramConfig;
use App\Services\WxMiniprogramMessageService;
use Illuminate\Http\Request;

class WxMiniprogramMessageController extends Controller
{
    private function returnMsgOkToWechat()
    {
        return 'success';
    }

    // 消息推送
    // 核心用于判断小程序的状态，发出报警使用
    public function messageCb($appid, Request $request)
    {
        $params = $request->input();

        $program = WxMiniprogramConfig::where('appid', $appid)->first();
        if (empty($program)) {
            return $this->returnMsgOkToWechat();
        }

        // 验证签名
        if (!WxMiniprogramMessageService::getInstance()->checkMsgSign($params, $program->token)) {
            return $this->returnMsgOkToWechat();
        }

        // 如果收到echostr，表示微信发来做接口验证的，按文档要求直接原样返回
        if (isset($params['echostr'])) {
            return $params['echostr'];
        }

        // 处理消息
        WxMiniprogramMessageService::getInstance()->handleMsg($program, $params);

        return $this->returnMsgOkToWechat();
    }
}
